package com.hmdp.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.hmdp.dto.Result;
import com.hmdp.entity.ShopType;
import com.hmdp.mapper.ShopTypeMapper;
import com.hmdp.service.IShopTypeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
@Slf4j
public class ShopTypeServiceImpl extends ServiceImpl<ShopTypeMapper, ShopType> implements IShopTypeService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private ShopTypeMapper shopTypeMapper;

    @Override
    public Result queryList() {
        //TODO 查询店铺类型列表
        List<String> shopTypeStrings = stringRedisTemplate.opsForList().range("shopTypeListKey", 0, -1);
        //TODO 查redis，存在，缓存命中，直接返回缓存数据
        if (CollectionUtils.isNotEmpty(shopTypeStrings)) {
            List<ShopType> collect = shopTypeStrings.stream()
                    .map(str -> JSONUtil.toBean(str, ShopType.class))
                    .collect(Collectors.toList());
            return Result.ok(collect);
        }
        //TODO redis中不存在，查询数据库
        QueryWrapper<ShopType> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByAsc("sort");
        List<ShopType> typeList = query().orderByAsc("sort").list();
        //TODO 数据库不存在,返回错误
        if (typeList == null || typeList.isEmpty()) {
            return Result.fail("店铺类型列表查询失败");
        }
        log.info("查询到店铺类型列表：{}", typeList);
        //List中的是String类型，进行类型转化
        //TODO 数据库存在，存入redis中
        List<String> collect = typeList.stream()
                .map(JSONUtil::toJsonStr)
                .collect(Collectors.toList());
        stringRedisTemplate.opsForList().rightPushAll("shopTypeListKey", collect);
        //TODO 返回结果
        return Result.ok(typeList);
    }
}
